<template>
  <div class="Pay">
    <van-nav-bar title="订单结算" left-text="返回" left-arrow @click-left="onClickLeft" fixed />
    <div class="pay-box">
      <div class="select-address">
        <div>
          <span @click="showSelectAddressList">选择地址 </span>
          <van-icon name="arrow" />
        </div>
        <div class="user-box">
          <div class="userinfo clearfix">
            <div class="user-name fl">{{ currentAddress.name }}</div>
            <div class="user-phone fl">{{ currentAddress.tel }}</div>
            <div class="default-address fl" v-if=" currentAddress.isDefault">默认</div>
          </div>
          <div class="detail-address">{{ currentAddress.address }}</div>
        </div>
      </div>

      <!-- 订单信息 -->
      <div class="order-info">
        <OrderList :count="productInfo.count" :total="productInfo.total">
          <div class="Onecard-box" v-for="(item,idx) in products" :key="idx">
            <van-card :price="item.price" :desc="item.enname" :title="item.name+' '+ item.rule" :thumb="item.small_img" :num="item.count" />
            <!-- <ProItem :item="item"></ProItem> -->
          </div>
        </OrderList>
      </div>

      <!-- 按钮 -->
      <div class="btn-box">
        <van-button type="primary" block round color="#0C34BA" @click="payBox">立即结算</van-button>
      </div>
      <van-popup is-link v-model="isOpen" closeable position="bottom">
        <div class="address-title">选择地址</div>
        <van-address-list v-model="chosenAddressId" :list="list" default-tag-text="默认" @add="newAddress" @select="selectAddress" />

      </van-popup>
    </div>

  </div>
</template>

<script>
import '@/assets/less/pay.less'
import OrderList from '@/components/OrderList.vue'
import request from '@/utils/reques'
import ProItem from '@/components/pro-item.vue'
import qs from 'qs'
export default {
  name: 'Pay',
  components: {
    OrderList,
    ProItem
  },
  data() {
    return {
      // 控制弹出的变量
      isOpen: false,
      // 地址列表
      list: [],
      // 选择当前地址的对象
      currentAddress: {},
      // 选择当前的地址的aid
      chosenAddressId: '',
      // 购物袋的sid
      sids: [],
      // 需要购买的商品数据
      products: [],
      // 商品的数量和总金额
      productInfo: {
        count: 0,
        total: 0
      }
    }
  },
  created() {
    // 截取查询数据
    this.sids = this.$route.query.sids.split('-')
    // 获取地址列表数据
    this.getAddressData()
    // 根据sid获取商品购物袋的数据
    this.getShopbagBySids()
  },
  methods: {
    // 展示列表
    showSelectAddressList() {
      this.isOpen = true
    },

    // 新增地址
    newAddress() {
      this.$router.push({ name: 'NewAddress' })
    },
    // 选择地址
    selectAddress(item, index) {
      this.isOpen = false
      this.currentAddress = item
    },
    onClickLeft() {
      this.$router.go(-1)
    },
    // 获取地址列表
    async getAddressData() {
      let tokenString = localStorage.getItem('token')

      if (!tokenString) {
        this.$toast('请先登录~')
        return this.$router.push({ name: 'Login' })
      }
      this.$toast.loading({
        message: '获取信息中',
        forbidClick: true,
        duration: 0
      })
      const { data: res } = await request.get('/findAddress', { params: { appkey: this.appkey, tokenString } })
      if (res.code == 700) {
        this.$router.push({ name: 'Login' })
      } else if (res.code == 20000) {
        res.result.map((v) => {
          v.isDefault = Boolean(v.isDefault)
          v.id = v.aid
          v.address = `${v.province}${v.city}${v.county}${v.addressDetail}`

          // 选择默认的地址
          if (v.isDefault) {
            this.currentAddress = v
            this.chosenAddressId = v.id
          }
        })
        this.list = res.result
      }
      this.$toast.clear()
    },
    // 根据sids查购物袋数据
    async getShopbagBySids() {
      let tokenString = localStorage.getItem('token')

      if (!tokenString) {
        this.$toast('请先登录~')
        return this.$router.push({ name: 'Login' })
      }
      this.$toast.loading({
        message: '获取信息中',
        forbidClick: true,
        duration: 0
      })
      const { data: res } = await request.get('/commitShopcart', { params: { appkey: this.appkey, tokenString, sids: JSON.stringify(this.sids) } })
      if (res.code == 700) {
        this.$router.push({ name: 'Login' })
      } else if (res.code == 50000) {
        // 拿到数据有两种情况（有商品/没商品）
        if (res.result.length == 0) {
          return this.$router.push({ name: 'Shopbag' })
        }
        res.result.map((v) => {
          this.productInfo.count += v.count
          this.productInfo.total += v.count * v.price
        })
        this.products = res.result
      } else {
        this.$toast(res.msg)
      }
      this.$toast.clear()
    },
    // 订单结算
    async pay() {
      let tokenString = localStorage.getItem('token')

      if (!tokenString) {
        this.$toast('请先登录~')
        return this.$router.push({ name: 'Login' })
      }
      this.$toast.loading({
        message: '获取信息中',
        forbidClick: true,
        duration: 0
      })
      const { data: res } = await request.post(
        '/pay',
        qs.stringify({
          appkey: this.appkey,
          tokenString,
          sids: JSON.stringify(this.sids),
          phone: this.currentAddress.tel,
          address: this.currentAddress.address,
          receiver: this.currentAddress.name
        })
      )
      if (res.code == 700) {
        this.$router.push({ name: 'Login' })
      } else {
        this.$toast(res.msg)
        setTimeout(() => {
          this.$router.push({ name: 'Order' })
        })
      }
    },
    // 结算提示
    payBox() {
      if (!this.chosenAddressId) {
        this.$toast('请选择地址')
        return
      }
      this.$dialog
        .confirm({
          title: '请确认订单',
          message: '是否进行结算'
        })
        .then(() => {
          this.pay()
        })
        .catch((err) => {})
    }
  }
}
</script>

<style>
</style>